package com.airbat.prize.utils;


import java.awt.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * color相关工具类
 */
public class MyColorUtils {

    //color对象池
    private static List<Color> colors = new LinkedList<>();

    //颜色相似度阈值
    private final static int SIMILAR_THRESHOLD = 5;

    //color对象池最大值
    private final static int MAXIMUM_SIZE = 440 / SIMILAR_THRESHOLD;

    /***
     * 根据指针获取RGBa格式的color
     * @param index 下标，当小于0或大于size时生成随机不相似的color
     */
    public static List<String> getRGBaColor(int index) {
        Color color = getColor(index);
        return getRGBaColor(color);
    }

    /***
     * 根据color,返回RGBa格式
     */
    public static List<String> getRGBaColor(Color color) {
        String rgba1 = String.format("rgba(%d, %d, %d, 0)", color.getRed(), color.getGreen(), color.getBlue());
        String rgba2 = String.format("rgba(%d, %d, %d, 1)", color.getRed(), color.getGreen(), color.getBlue());
        return Arrays.asList(rgba1, rgba2);
    }

    private static int getColorSize() {
        return colors.size();
    }

    /***
     * 根据指针获取color对象
     * @param index 下标，当小于0或大于size时生成随机不相似的color
     */
    public static Color getColor(int index) {
        if (index < 0 || index >= getColorSize()) {
            return getRandomColor();
        }
        return colors.get(index);
    }

    /***
     * 生成随机color对象，存入对象池并返回
     * @return 随机color对象
     */
    public static synchronized Color getRandomColor() {
        Random random = new Random();
        while (colors.size() < MAXIMUM_SIZE) {
            int r = random.nextInt(256);
            int g = random.nextInt(256);
            int b = random.nextInt(256);
            Color color = new Color(r, g, b);

            if (!isSimilarColor(color)) {
                colors.add(color);
                return color;
            }
            color = null;
        }
        return colors.get(0);
    }

    /***
     * 判断color对象是否与colors中的对象颜色相似
     * @param color 要判断的颜色
     */
    private static synchronized boolean isSimilarColor(Color color) {
        for (Color c : colors) {
            double r = c.getRed() - color.getRed();
            double g = c.getGreen() - color.getGreen();
            double b = c.getBlue() - color.getBlue();
            double sqrt = Math.sqrt(r * r + g * g + b * b);
            //值越小颜色越相近
            if (sqrt < SIMILAR_THRESHOLD) {
                return true;
            }
        }
        return false;
    }

}
